package com.tmt.im.manager.service;

import com.tmt.data.jpa.service.TmtJpaDataService;
import com.tmt.im.jpa.entity.IMFriendGroup;
import com.tmt.im.jpa.entity.IMUser;
import com.tmt.im.jpa.repository.IMFriendGroupRepo;
import com.tmt.im.manager.controller.vo.FriendGroupInfoVo;
import com.tmt.im.manager.controller.vo.NewFriendGroupRequest;
import com.tmt.im.manager.controller.vo.UpdateFriendGroupRequest;
import com.tmt.im.manager.helper.PrincipalHelper;
import com.tmt.im.manager.mapstruct.IMFriendGroupMapStruct;
import com.tmt.springboot.common.restful.ExecuteResult;
import com.tmt.springboot.common.restful.IExecuteResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;

import java.security.Principal;
import java.text.MessageFormat;
import java.util.List;
import java.util.Objects;

/**
 * @Description TODO
 * @Author wuyi
 * @Date 2024/8/24 17:42
 * @Version 1.0
 **/
@Service
@Deprecated(since="被IMFriendGroupIgniteService类替代了")
public class IMFriendGroupService extends TmtJpaDataService<IMFriendGroup, Long> {

    private final IMFriendGroupRepo imFriendGroupRepo;

    private final IMFriendGroupMapStruct imFriendGroupMapStruct;

    public IMFriendGroupService(IMFriendGroupRepo mainRepo,
                                IMFriendGroupMapStruct imFriendGroupMapStruct) {
        super(mainRepo);
        this.imFriendGroupRepo = mainRepo;
        this.imFriendGroupMapStruct = imFriendGroupMapStruct;
    }

    @Transactional(rollbackFor = Exception.class)
    public IExecuteResult<Boolean> addFriendGroup(NewFriendGroupRequest request, Principal principal) {
        Long currentUserId = PrincipalHelper.getCurrentUserId(principal);
        IMUser creator = IMUser.builder()
                .id(currentUserId)
                .build();
        try {
            IMFriendGroup group = IMFriendGroup.builder()
                    .name(request.getName())
                    .note(request.getNote())
                    .creator(creator)
                    .build();
            imFriendGroupRepo.save(group);
        } catch (Exception ex) {
            String info = ex.getMessage();
            if (info != null && info.contains("Duplicate entry")) {
                if (info.contains("PRIMARY")) {
                    info = MessageFormat.format("分组名称重复:{0}", request.getName());
                }
            }
            return ExecuteResult.failure(400, info, false);
        }
        return ExecuteResult.success(true);
    }

    @Transactional(rollbackFor = Exception.class)
    public IExecuteResult<Boolean> updateFriendGroup(UpdateFriendGroupRequest request, Principal principal) {
        Long currentUserId = PrincipalHelper.getCurrentUserId(principal);
        try {
            IMFriendGroup group = imFriendGroupRepo.findById(request.getId()).orElse(null);
            if (group == null) {
                return ExecuteResult.failure(400, "目标分组不存在", false);
            }
            if (!Objects.equals(group.getCreator().getId(), currentUserId)) {
                return ExecuteResult.failure(400, "不能修改他人的好友分组", false);
            }
            if (StringUtils.hasText(request.getName())) {
                group.setName(request.getName());
            }
            if (StringUtils.hasText(request.getNote())) {
                group.setNote(request.getNote());
            }
            imFriendGroupRepo.save(group);
        } catch (Exception ex) {
            String info = ex.getMessage();
            if (info != null && info.contains("Duplicate entry")) {
                if (info.contains("PRIMARY")) {
                    info = MessageFormat.format("分组名称重复:{0}", request.getName());
                }
            }
            return ExecuteResult.failure(400, info, false);
        }
        return ExecuteResult.success(true);
    }

    @Transactional(readOnly = true)
    public IExecuteResult<List<FriendGroupInfoVo>> listFriendGroup(Principal principal) {
        Long currentUserId = PrincipalHelper.getCurrentUserId(principal);
        List<IMFriendGroup> groupList = imFriendGroupRepo.findAllByCreatorId(currentUserId);
        List<FriendGroupInfoVo> voList = imFriendGroupMapStruct.toFriendGroupInfoVos(groupList);
        return ExecuteResult.success(voList);
    }

    @Transactional(rollbackFor = Exception.class)
    public IExecuteResult<Boolean> deleteFriendGroup(Long groupId, Principal principal){
        Long currentUserId = PrincipalHelper.getCurrentUserId(principal);
        IMFriendGroup group = imFriendGroupRepo.findById(groupId).orElse(null);
        if (group == null) {
            return ExecuteResult.failure(400, "目标分组不存在", false);
        }
        if (!Objects.equals(group.getCreator().getId(), currentUserId)) {
            return ExecuteResult.failure(400, "不能删除他人的好友分组", false);
        }
        imFriendGroupRepo.delete(group);
        return ExecuteResult.success(true);
    }
}
